using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace TCC.Framework
{
    /// <summary>
    /// UI面板基类
    /// </summary>
    public class BasePanel
    {
        /// <summary>
        /// UI实体
        /// </summary>
        public GameObject UIEntity { get; set; }

        protected Dictionary<string, UIBehaviour> uiComponents;

        public TFunc<int, string> ChangeText;

        public virtual bool StickyTopic { get; protected set; } = false;

        /// <summary>
        /// 初始化 UI实体被创建时执行
        /// </summary>
        public virtual void OnInit()
        {
            uiComponents = new Dictionary<string, UIBehaviour>();
            GetAllUIBehaviour();
        }

        /// <summary>
        /// 界面显示时
        /// </summary>
        public virtual void OnEnter(params object[] args)
        {

        }

        /// <summary>
        /// 界面暂停 置于其它界面之下
        /// </summary>
        public virtual void OnPause(params object[] args)
        {

        }

        /// <summary>
        /// 界面继续
        /// </summary>
        public virtual void OnResume(params object[] args)
        {

        }

        /// <summary>
        /// 退出界面 界面关闭
        /// </summary>
        public virtual void OnExit(params object[] args)
        {

        }

        /// <summary>
        /// 获取所有UIBehaviour
        /// </summary>
        private void GetAllUIBehaviour()
        {
            foreach (var item in UIEntity.GetComponentsInChildren<UIBehaviour>(true))
            {
                if (uiComponents.ContainsKey(item.ID))
                    throw new UnityException($"在同一个Panel下发现相同的UIBehaviourID{item.ID}");
                else
                    uiComponents.Add(item.ID, item);
            }
        }

        /// <summary>
        /// 获取UIBehaviour
        /// </summary>
        /// <param name="uiId"></param>
        /// <returns></returns>
        protected UIBehaviour GetUIBehaviour(string uiId)
        {
            if (uiComponents.ContainsKey(uiId))
                return uiComponents[uiId];
            else
            {
                Log.Error($"{UIEntity.name}下未找到ID为{uiId}的UIBehaviour！");
                return null;
            }
        }

        /// <summary>
        /// 切换语言
        /// </summary>
        public virtual void ChangedWord()
        {
            foreach (var item in uiComponents.Values)
            {
                string text = ChangeText?.Invoke(item.GetLanguageId());
                if (string.IsNullOrEmpty(text)) return;
                item.SetTextStr(text);
            }
        }
    }
}
